from datetime import datetime
from app.extensions import db

class User(db.Model):
    """用户表模型"""
    __tablename__ = 'user'
    
    user_id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='用户唯一标识')
    username = db.Column(db.String(50), unique=True, nullable=False, comment='用户名')
    password = db.Column(db.String(255), nullable=False, comment='加密密码')
    mobile = db.Column(db.String(20), unique=True, nullable=True, comment='手机号')
    email = db.Column(db.String(100), unique=True, nullable=True, comment='邮箱')
    role = db.Column(db.Enum('家长', '学生', name='user_roles'), 
                    nullable=False, default='家长', comment='用户角色')
    reg_time = db.Column(db.DateTime, default=datetime.now, comment='注册时间')

    # 关系定义（逻辑层面）
    students = db.relationship('Student', backref='parent', lazy='dynamic')
    contents = db.relationship('Content', backref='creator', lazy='dynamic')

    def to_dict(self):
        return {
            'user_id': self.user_id,
            'username': self.username,
            'mobile': self.mobile,
            'email': self.email,
            'role': self.role,
            'reg_time': self.reg_time.strftime('%Y-%m-%d %H:%M:%S')
        }

    def __repr__(self):
        return f'<User {self.username} ({self.role})>'